package utils

import (
	"context"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/sms/bytes"
	"github.com/qiniu/go-sdk/v7/storage"
	"io"
	"mime/multipart"
)

func Upload(file *multipart.FileHeader) (string, error) {
	putPolicy := storage.PutPolicy{
		Scope: "wm23",
	}
	mac := qbox.NewMac("poZkwfsgOtOe6T5SBZepZuRL2aE9VRkfjnmtgyea", "IRY6M3-qRsQrwZ0TSzJy1vcPFMpNf9CG0YkO2z3_")
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Region = &storage.ZoneHuadongZheJiang2
	// 是否使用https域名
	cfg.UseHTTPS = true
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{}

	f, _ := file.Open()
	b, _ := io.ReadAll(f)

	err := formUploader.Put(context.Background(), &ret, upToken, file.Filename, bytes.NewReader(b), file.Size, &putExtra)
	if err != nil {
		return "", err
	}
	fmt.Println(ret.Key, ret.Hash)
	return "http://s0a7y00j1.bkt.clouddn.com/" + ret.Key, nil
}
